package com.hogan.hoganproject.base.rx;


import com.hogan.hoganproject.base.api.protocol.BaseProtocol;
import com.hogan.hoganproject.base.api.protocol.ConcreteProtocol;
import com.hogan.hoganproject.base.api.protocol.ServerApiException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Author: chenhu
 * Time: 2020/9/1 17:52
 * 线程调试，统一返回数据
 */
public class SchedulersCompat {

    public static ObservableTransformer applyIoSchedulers() {
        return  transformer;
    }

    private static ObservableTransformer transformer = new ObservableTransformer() {
        @Override
        public ObservableSource apply(Observable observable) {

            return observable.map(new Function<BaseProtocol, ConcreteProtocol>() {

                @Override
                public ConcreteProtocol apply(BaseProtocol baseProtocol) throws Exception {
                    return new ConcreteProtocol(baseProtocol);
                }
            }).flatMap(new Function<ConcreteProtocol, Observable>() {

                @Override
                public Observable apply(ConcreteProtocol concreteProtocol) throws Exception {
                    Object object = concreteProtocol.parsed();
                    if (object instanceof ServerApiException) {
                        return Observable.error((ServerApiException) object);
                    } else {
                        return Observable.just(object);
                    }
                }
            }).subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());

        }
    };
}
